package com.xydtech.ecard.ecard.controller;

import com.alibaba.fastjson.JSONObject;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import com.xydtech.common.annotation.RsaRequest;
import com.xydtech.common.annotation.string.StringUtil;
import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.enums.ResultStatus;
import com.xydtech.common.model.ResponseModel;
import com.xydtech.common.utils.DateUtils;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.ecard.ecard.domain.EcardApiRuleExecute;
import com.xydtech.ecard.user.domain.EcardApiUserInfo;
import com.xydtech.ecard.user.service.IEcardApiUserService;
import com.xydtech.rule.domain.RuleElementsGroup;
import com.xydtech.rule.domain.RuleElementsGroupDetail;
import com.xydtech.rule.domain.RuleElementsItems;
import com.xydtech.rule.service.IRuleElementsGroupDetailService;
import com.xydtech.rule.service.IRuleElementsGroupService;
import com.xydtech.system.domain.SysWechatApplet;
import com.xydtech.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @className：EcardRuleElementsController
 * @description：电子名片规则信息接口
 * @author：yjs
 * @date：2024/6/11 8:59
 * @since：1.8
 * @version：1.0
 */
@Controller
@Slf4j
@Api(tags = "电子名片-规则信息接口")
@RequestMapping("/ecardSaasApi/rule")
public class EcardRuleElementsController extends EcardApiBaseController {
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IEcardApiUserService ecardApiUserService;
    @Autowired
    private IRuleElementsGroupService ruleElementsGroupService;
    @Autowired
    private IRuleElementsGroupDetailService ruleElementsGroupDetailService;

    /**
     * 查询规则组数据
     *
     * @param json
     * @return
     */
    @PostMapping(value = "/getRuleFeatureGroup")
    @ApiOperation(value = "电子名片-查询规则组数据", notes = "电子名片-查询规则组数据")
    @ResponseBody
    @RsaRequest
    public ResponseModel getRuleFeatureGroup(@RequestBody String json) {
        log.info("接口请求时间-------" + DateUtils.getTime());
        try {
            String salt = getSalt();//盐值
            if (StringUtil.objIsNullOrEmpty(json)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            JSONObject jsonObject = JSONObject.parseObject(json);
            //组合编码
            String groupCode = jsonObject.getString("groupCode");
            //根据appId获取deptId
            String currentUserId = getCurrentUserId();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            //当前小程序id
            SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
            String appId = wechatApplet.getAppid();
            if (StringUtils.isEmpty(appId)) {
                return ResponseModel.error(ResultStatus.PARAMETER_ERROR);
            }
            //法人机构信息
            SysDept secondLevelDept = deptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //获取法人机构的ID
            Long legalManDeptId = secondLevelDept.getDeptId();
            RuleElementsGroup ruleElementsGroup = new RuleElementsGroup();
            ruleElementsGroup.setDeptId(legalManDeptId);
            ruleElementsGroup.setGroupCode(groupCode);
            ruleElementsGroup.setSts("1");
            List<RuleElementsGroup> ruleElementsGroups = ruleElementsGroupService.selectRuleElementsGroupList(ruleElementsGroup);
            if (ruleElementsGroups == null || ruleElementsGroups.size() == 0) {
                return ResponseModel.error("操作失败，未查询到规则组数据！");
            }
            RuleElementsGroupDetail ruleElementsGroupDetail = new RuleElementsGroupDetail();
            ruleElementsGroupDetail.setGroupId(ruleElementsGroups.get(0).getId());
            List<RuleElementsGroupDetail> details = ruleElementsGroupDetailService.selectRuleElementsGroupDetailList(ruleElementsGroupDetail);
            return ResponseModel.okToJSONArray(details);
        } catch (Exception ex) {
            log.error("电子名片-查询规则组数据接口出错：" + ex.getMessage() + "详细内容：" + ex);
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * @description：电子名片-执行规则测试返回结果值
     * @author：yjs
     * @date：2024/6/11 9:35
     */
    @PostMapping(value = "/getRuleTestOutcome")
    @ApiOperation(value = "电子名片-执行规则测试返回结果值", notes = "电子名片-执行规则测试返回结果值")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel getRuleTestOutcome(@RequestBody EcardApiRuleExecute ecardApiRuleExecute) {
        log.info("接口请求时间-------" + DateUtils.getTime());
        try {
            //查询规则组数据
            RuleElementsGroup ruleElementsGroups = ruleElementsGroupService.selectRuleElementsGroupById(ecardApiRuleExecute.getGroupId());
            //获取规则要素数据
            List<RuleElementsItems> ruleElementsList = ecardApiRuleExecute.getRuleElementsItems();
            if (ruleElementsList == null || ruleElementsList.size() == 0) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            // 一个参数是是否开启高精度默认false，第二个参数是是否开启trace。
            ExpressRunner runner = new ExpressRunner(false, false);
            DefaultContext<String, Object> context = new DefaultContext<>();
            for (RuleElementsItems ruleElementsItems : ruleElementsList) {
                //判断要素项类型 1-数字型 2-字符型
                if ("1".equals(ruleElementsItems.getElementsType())) {
                    context.put(ruleElementsItems.getElementsName(), Integer.valueOf(ruleElementsItems.getElementsValue()));
                } else {
                    context.put(ruleElementsItems.getElementsName(), ruleElementsItems.getElementsValue());
                }
            }
            log.info("参数值：" + context);
            String express = ruleElementsGroups.getRuleFormulas().replaceAll("\\r|\\n|\\t", " ");
            log.info("测试公式：" + express);
            Object outcome = runner.execute(express, context, null, false, false);
            long round = Math.round(Double.valueOf(outcome.toString()));
            if (round < 0) {
                round = 0;
            }
            log.info("电子名片-执行规则测试返回结果值：" + round);
            return ResponseModel.ok(round);
        } catch (Exception ex) {
            log.error("电子名片-执行规则测试返回结果值接口出错：" + ex.getMessage() + "详细内容：" + ex);
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }
}
